<?php

/**
 * 图片处理
 *
 * Author: Surfin
 * Datetime: 16/10/20 下午2:21
 */

namespace Services;

use Endroid\QrCode\QrCode;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;

class Images
{

    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * @param int $width 画布宽
     * @param int $height 画布高
     * @param string $text 文字
     * @param string $picture_name 图片名称
     * @param int $x 字体距离左的位置
     * @param int $y 字体距离右的位置
     * @param int $font_size 字体大小
     * @param string $font 字体类型
     */
    function generateAvatar($width = 60, $height = 60, $text = 'Hello World', $picture_name = '', $x = null , $y = null,  $font_size = 12, $font = "../web/assets/fonts/simsun.ttc")
    {
        $myImage = ImageCreate($width, $height); //参数为宽度和高度
        ImageColorAllocate($myImage, 255, 255, 255);//第一次背景上色
        //第二次字体上色
        //$white = ImageColorAllocate($myImage, 255, 255, 255);
        $black = ImageColorAllocate($myImage, 0, 0, 0);
        // $red=ImageColorAllocate($myImage, 255, 0, 0);
        // $green=ImageColorAllocate($myImage, 0, 255, 0);
        // $blue=ImageColorAllocate($myImage, 0, 0, 255);
        $angle = 0;
        //头像默认居中显示
        if($x == null || $y == null){
            //获取文字段宽高
            $box = imagettfbbox($font_size, $angle, $font, $text);
            $min_x = min( array($box[0], $box[2], $box[4], $box[6]) );
            $max_x = max( array($box[0], $box[2], $box[4], $box[6]) );
            $min_y = min( array($box[1], $box[3], $box[5], $box[7]) );
            $max_y = max( array($box[1], $box[3], $box[5], $box[7]) );
            $textWidth  = ( $max_x - $min_x );
            $textHeight = ( $max_y - $min_y );
            $x = ($width - $textWidth)/2;
            $y = ($height + $textHeight)/2;
        }

        imagettftext($myImage, $font_size, $angle, $x, $y, $black, $font, $text);
        imagepng($myImage, __DIR__ . "/../../web/" . $picture_name);
    }

    /**
     * 二维码
     *
     * @param string $text
     * @param int $size
     * @param string $title
     */
    public function qrcode($text = 'http://www.baidu.com', $size = 300, $title = '')
    {
        $qrCode = new QrCode();
        $qrCode
            ->setText($text)
            ->setSize($size)
            ->setPadding(10)
            ->setErrorCorrection('high')
            ->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0])
            ->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0])
            ->setLabel($title)
            ->setLabelFontSize(16)
            ->setImageType(QrCode::IMAGE_TYPE_PNG)
        ;

        // now we can directly output the qrcode
        header('Content-Type: '.$qrCode->getContentType());
        $qrCode->render();
    }

}
